package com.dk.academic.controller;

import com.dk.academic.common.Utility;

import com.dk.academic.controller.base.SuperController;
import com.dk.academic.model.Article;
import com.dk.academic.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;


@Controller
@RequestMapping("/uploading")
public class UploadController extends SuperController {

    @Autowired
    private ArticleService articleService;


    @RequestMapping("")
    public String index(Model model) {
        if (session.getAttribute("article") != null) {
            // 将数据保存
            articleService.insertArticle((Article)session.getAttribute("article"));
            // 移除该session
            session.removeAttribute("article");
        }
        model.addAttribute("articles", articleService.selectArticles());
        model.addAttribute("temp", "hello");
        return "uploading";
    }

    @RequestMapping("/enw")
    @ResponseBody
    public String enwUpload(@RequestParam("file")MultipartFile file, Model model) {
        System.out.println("解析开始运行");
        Article article;
        // 判断当前所传输的文件是否为空
        if (file.isEmpty()) {
            return toJson(false);
        }
        try {
            // 如果不为空创建一个新的临时File文件，用来转储MultipartFile类型文件
            File temp = new File("C:\\Users\\Administrator\\Desktop\\学术论坛/temp.txt");
            // 利用commons.ip的api获取multipartFile的输出流并赋值给temp临时文件
            org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), temp);
            // 利用工具类进行解析，使用实体类Article接收回调数据
            article = Utility.enwAnalysis(temp);
            // 将解析出的article保存在session中，用来确认修改
            session.setAttribute("article",article);
            // 插入数据
            //articleService.insertArticle(article);
            // 删除该临时文件，结束整个过程
            temp.delete();
        } catch (Exception e) {
            return toJson(false);
        }

        return toJson(article);
    }

}
